package com.dingdang.shiro;
import com.dingdang.entity.TbAdmin;
import com.dingdang.mapper.TbAdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/*
 * 自定义的realm类，需要继承AuthenticatingRealm(只有登录功能)    AuthorizingRealm（登录和授权）
 * */
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private TbAdminMapper tbAdminMapper;

    //授权方法yn
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证方法  调用subject的login方法后进入
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        //查询username 是否存在
        System.out.println(username);
        TbAdmin tbAdmin = tbAdminMapper.selectTbUserByName(username);
        //如果tPerson == null 说明数据库没用这个账号
        if (tbAdmin == null) {
            return null;
        }
        //第一个实体类
        //第二个数据库的密码
        //第三个数据库的盐
        //第四个名字
        return new SimpleAuthenticationInfo(tbAdmin, tbAdmin.getPassword(), ByteSource.Util.bytes(tbAdmin.getSalt()), tbAdmin.getUsername());
    }
}
